
#include "config.h"
#include "app_config.h"

#include "STC32G_RTC.h"
#include "STC32G_NVIC.h"

#include "drv_rtc.h"
#include "debug.h"

bit B_1S;
bit B_Alarm;
static calendar_obj calendar;

void rtc_init(void)
{
	RTC_InitTypeDef		RTC_InitStructure;
	RTC_InitStructure.RTC_Clock  = RTC_IRC32KCR;	//RTC 时钟, RTC_IRC32KCR, RTC_X32KCR
	RTC_InitStructure.RTC_Enable = ENABLE;			//RTC功能使能,   ENABLE, DISABLE
	RTC_InitStructure.RTC_Year   = 25;					//RTC 年, 00~99, 对应2000~2099年
	RTC_InitStructure.RTC_Month  = 04;					//RTC 月, 01~12
	RTC_InitStructure.RTC_Day    = 22;					//RTC 日, 01~31
	RTC_InitStructure.RTC_Hour   = 11;					//RTC 时, 00~23
	RTC_InitStructure.RTC_Min    = 59;					//RTC 分, 00~59
	RTC_InitStructure.RTC_Sec    = 55;					//RTC 秒, 00~59
	RTC_InitStructure.RTC_Ssec   = 00;					//RTC 1/128秒, 00~127

	RTC_InitStructure.RTC_ALAHour= 00;					//RTC 闹钟时, 00~23
	RTC_InitStructure.RTC_ALAMin = 00;					//RTC 闹钟分, 00~59
	RTC_InitStructure.RTC_ALASec = 00;					//RTC 闹钟秒, 00~59
	RTC_InitStructure.RTC_ALASsec= 00;					//RTC 闹钟1/128秒, 00~127
	RTC_Inilize(&RTC_InitStructure);
	NVIC_RTC_Init((RTC_ALARM_INT|RTC_SEC_INT), Priority_0);		//中断使能, RTC_ALARM_INT/RTC_DAY_INT/RTC_HOUR_INT/RTC_MIN_INT/RTC_SEC_INT/RTC_SEC2_INT/RTC_SEC8_INT/RTC_SEC32_INT/DISABLE; 优先级(低到高) Priority_0,Priority_1,Priority_2,Priority_3
}

void rtc_ntp_sync(struct app_t* app)
{

}

void rtc_calendar_get(calendar_obj* obj)
{
    obj->year = YEAR + 2000;
    obj->month = MONTH;
    obj->day = DAY;

    obj->hour = HOUR;
    obj->min = MIN;
    obj->sec = SEC;
    obj->ssec = SSEC;
}

void rtc_calendar_printf(calendar_obj* obj)
{
    log_d("datetme:%04d/%02d/%02d  %02d:%02d:%02d\n", obj->year, obj->month, obj->day, \
        obj->hour, obj->min, obj->sec);
}

uint8_t rtc_datatime_available(void)
{
    return 0;
}

void rtc_task(void)
{
    if (B_1S) {
        B_1S = 0;
        rtc_calendar_get(&calendar);
        // rtc_calendar_printf(&calendar);
    }

    if (B_Alarm) {
        B_Alarm = 0;
    }

}





//========================================================================
// 函数: RTC_ISR_Handler
// 描述: RTC中断函数.
// 参数: none.
// 返回: none.
// 版本: V1.0, 2022-03-21
//========================================================================
void RTC_ISR_Handler (void) interrupt RTC_VECTOR
{
	// TODO: 在此处添加用户代码
	if(RTCIF & 0x80)    //闹钟中断
	{
		// P01 = !P01;
		RTCIF &= ~0x80;
		B_Alarm = 1;
	}

	if(RTCIF & 0x08)    //秒中断
	{
		// P00 = !P00;
		RTCIF &= ~0x08;
		B_1S = 1;
	}
}
